<template>
  <div id="doAnswerPage">
    <a-card>
      <h1>{{ app.appName }}</h1>
      <p>{{ app.appDesc }}</p>
      <h2>{{ current }}、{{ currentQuestion?.title }}</h2>

      <a-checkbox-group
        direction="vertical"
        v-model="currentAnswer"
        :options="questionOptions"
        @change="doCheckboxChange"
      />

      <div style="margin-top: 24px">
        <a-space size="large">
          <a-button
            type="primary"
            circle
            v-if="current < questionContent.length"
            :disabled="!currentAnswer.length"
            @click="current += 1"
            >下一题</a-button
          >
          <a-button
            type="primary"
            circle
            v-if="current === questionContent.length"
            :loading="submitting"
            :disabled="!currentAnswer.length"
            @click="doSubmit"
          >
            {{ submitting ? "提交中" : "提交" }}
          </a-button>
          <a-button v-if="current > 1" circle @click="current -= 1"
            >上一题</a-button
          >
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  reactive,
  watchEffect,
  withDefaults,
  defineProps,
} from "vue";
import { useRouter } from "vue-router";
import message from "@arco-design/web-vue/es/message";
import API from "@/api";
import { getAppVoByIdUsingGet } from "@/api/appController";
import { listQuestionVoByPageUsingPost } from "@/api/questionController";
import {
  addUserAnswerUsingPost,
  generateUserAnswerIdUsingGet,
} from "@/api/userAnswerController";

interface Props {
  appId: string;
}
const props = withDefaults(defineProps<Props>(), { appId: () => "" });
const router = useRouter();

const app = ref<API.AppVO>({});
const questionContent = ref<API.QuestionContentDTO[]>([]);
const current = ref(1);
const currentQuestion = ref<API.QuestionContentDTO>({});
const questionOptions = computed(
  () =>
    currentQuestion.value?.options?.map((option) => ({
      label: `${option.key}. ${option.value}`,
      value: option.key,
    })) || []
);
const currentAnswer = ref<string[]>([]);
const answerList = reactive<string[]>([]);
const submitting = ref(false);
const id = ref<number>();

const generateId = async () => {
  const res = await generateUserAnswerIdUsingGet();
  if (res.data.code === 0) id.value = res.data.data;
};

watchEffect(() => {
  generateId();
});

const loadData = async () => {
  const res1 = await getAppVoByIdUsingGet({ id: props.appId });
  if (res1.data.code === 0) app.value = res1.data.data;

  const res2 = await listQuestionVoByPageUsingPost({
    appId: props.appId,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res2.data.code === 0)
    questionContent.value = res2.data.data.records[0].questionContent;
};

watchEffect(() => {
  loadData();
});

// watchEffect(() => {
//   currentQuestion.value = questionContent.value[current.value - 1];
//   currentAnswer.value = answerList[current.value - 1] || [];
// });

watchEffect(() => {
  currentQuestion.value = questionContent.value[current.value - 1];

  const raw = answerList[current.value - 1];
  currentAnswer.value = raw ? raw.split(",") : [];
});

// const doCheckboxChange = (value: string[]) => {
//   answerList[current.value - 1] = value;
// };

const doCheckboxChange = (value: string[]) => {
  answerList[current.value - 1] = value.join(","); // ✅ 转为字符串 "A,C"
};

const doSubmit = async () => {
  submitting.value = true;
  const res = await addUserAnswerUsingPost({
    appId: props.appId,
    choices: answerList,
    id: id.value,
  });
  if (res.data.code === 0) {
    router.push(`/answer/result/${res.data.data}`);
  } else {
    message.error("提交失败：" + res.data.message);
  }
  submitting.value = false;
};
</script>
